package NetWorkTest;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpClient {
    //指定IP地址和端口号
    //IP代表你要将请求发送到哪个服务器
    //端口号代表要给哪个应用程序/进程
    Socket socket = null;

    public TcpClient() throws IOException {
        socket = new Socket("127.0.0.1",8096);
    }

    public void start() throws IOException {
        System.out.println("客户端启动!!!");
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            Scanner scanner = new Scanner(System.in);//用户输入信息
            Scanner scannerNet = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);
            while(true){
                //客户端建立请求
                System.out.print(">");
                String request = scanner.next();
                //将请求发送给服务器
                printWriter.println(request);
                //刷新缓冲区
                printWriter.flush();
                //服务器做出响应-客户端进行接收
                String response = scannerNet.next();
                //将响应显示给用户
                System.out.printf("req = %s ; rep = %s\n",request,response);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        TcpClient tcpClient = new TcpClient();
        tcpClient.start();
    }

}
